package concurrent.automic;

import java.util.concurrent.atomic.AtomicReference;
import java.util.function.UnaryOperator;

/**
 * \* User: Administrator
 * <p>
 * \* Date: 2020/11/25
 * <p>
 * \* Time: 14:03
 * <p>
 * \* Description:
 * \
 */
public class AtomicRefrenceDemo {
    //static volatile DebitCard card = new DebitCard("622225", 100);
    static AtomicReference<DebitCard> card = new AtomicReference<>(new DebitCard("622225", 100));

    public static void main(String[] args) throws InterruptedException {
        //多线程不安全
//        for (int i = 0; i < 10000; i++) {
//            new Thread(() -> {
//                card.setAmount(card.getAmount() + 1);
//            }).start();
//        }
        //synchronized
//        for (int i = 0; i < 10000; i++) {
//            new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    synchronized (AtomicRefrenceDemo.class) {
//                        card.setAmount(card.getAmount() + 1);
//                    }
//                }
//            }).start();
//        }
        for (int i = 0; i <5000; i++) {
            new Thread(()->{
                //此处必须是new对象 参考源码 apply方法返回一个新的对象 然后再做替换
                // V prev, next;
                //        do {
                //            prev = get();
                //            next = updateFunction.apply(prev);
                //        } while (!compareAndSet(prev, next));
                card.updateAndGet(debitCard -> new DebitCard(debitCard.getAccount(), debitCard.getAmount() + 1));
            }).start();
        }
        Thread.sleep(5000);
        System.out.println(card.get().getAmount());
    }
}
